<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Menu information class.
 *
 * Menu information's CRUD.
 */
class Menu_model extends CI_Model
{
	private $db_name = 'k9deploy_new';
	private $table = 'menu';
	private $db = null;
	
	/**
	 * Constructor
	 *
	 * Sets the database used for saving account information.
	 */
	public function __construct()
	{
		parent::__construct();
		
		$this->db = $this->load->database($this->db_name, TRUE);
		
		$this->load->library('memcached_lib');
	}
	
	public function get()
	{
		if($data = $this->memcached_lib->get('packmenu')){
// 			var_dump($data);
			return $data;
		}
		
		$level_1_menus = $this->db->select('id, c_name, m_name, menu_name')
									->where('menu_level', 1)
									->get($this->table)
									->result_array();
		foreach ($level_1_menus as & $i)
		{
			$level_2_menus = $this->db->select('id, c_name, m_name, menu_name')
												->where('menu_level', 2)
												->where('menu_parent', $i['id'])
												->get($this->table)
												->result_array();
			$i['sub_menus'] = $level_2_menus;
		}
		
		$this->memcached_lib->add('packmenu', $level_1_menus, $this->config->item('cache_time'));
		
		return $level_1_menus;
	}
	
	public function get_second_menus()
	{
		$level_1_menus = $this->db->select('id, c_name, m_name, menu_name')
									->where('menu_level', 1)
									->get($this->table)
									->result_array();
		
		$ret = array();
		foreach ($level_1_menus as & $i)
		{
			$level_2_menus = $this->db->select('id, menu_name')
										->where('menu_level', 2)
										->where('menu_parent', $i['id'])
										->get($this->table)
										->result_array();
			$ret = array_merge($ret, $level_2_menus);
		}
	
		return $ret;
	}
	
	public function get_menu_id($cname, $level=2)
	{
		$ret = $this->db->select('id')->where(array('c_name'=>$cname, 'menu_level'=>$level))->get($this->table)->row_array();
		return $ret['id'];
	}
	
	/**
	 * add new information
	 *
	 * @param	array	new information
	 * @return	object
	 */
	public function add($data=array())
	{
		if(empty($data))
			return false;
		
		$this->memcached_lib->delete('menu');
	
		return $this->db->insert($this->table, $data);
	}
	
	/**
	 * update information regarding id
	 *
	 * @param	integer	id
	 * @param	array	new information
	 * @return	object
	 */
	public function update($id = 0, $data)
	{
		$this->memcached_lib->delete('menu');
		
		$this->db->where(array('id' => $id));
		$this->db->update($this->table, $data);
		return $id;
	}
}